package com.sephiron.clocksynchronizer;

import java.util.ArrayList;
import java.util.UUID;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;

public class TimeSyncPagerActivity extends FragmentActivity {
	private VariableViewPager mViewPager;
	private ArrayList<Cctv> mCctvs;
	
	private boolean editable;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mViewPager = new VariableViewPager(this);
		mViewPager.setId(R.id.variableViewPager);
		setContentView(mViewPager);
		
		mCctvs = CctvLab.get(this).getCctvs();
		editable = getIntent().getBooleanExtra(TimeSyncFragment.EXTRA_EDIT_MODE, false);
		
		FragmentManager fm = getSupportFragmentManager();
		mViewPager.setAdapter(new FragmentStatePagerAdapter(fm) {
			
			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return mCctvs.size();
			}
			
			@Override
			public Fragment getItem(int pos) {
				// TODO Auto-generated method stub
				Cctv cctv = mCctvs.get(pos);
				if (editable) {
					editable = false;
					return TimeSyncFragment.newInstance(cctv.getId(), true);	
				} else {
					return TimeSyncFragment.newInstance(cctv.getId(), false);
				}
				
			}
		});
		
		UUID cctvId = (UUID)getIntent()
			 .getSerializableExtra(TimeSyncFragment.EXTRA_CCTV_ID);
		for (int i = 0; i < mCctvs.size(); i++) {
			if (mCctvs.get(i).getId().equals(cctvId)) {
				mViewPager.setCurrentItem(i);
				
				if (mCctvs.get(i).getCctvName() != null) {
					setTitle(mCctvs.get(i).getCctvName());
				}
				break;
			}
		}
		
		mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int pos) {
				Cctv cctv = mCctvs.get(pos);
				if (cctv.getCctvName() != null) {
					setTitle(cctv.getCctvName());
				}
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
			}
		});
	}
}